// pages/mine/login/login.js
import {
  Toast
} from 'wuss-weapp';
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      theme: app.globalData.theme
    });
    let than = this
    // 查看是否授权
    wx.getSetting({
      success (res){
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function(res) {
              app.globalData.wxUserInfo = res.userInfo
              than.login()
            }
          })
        }
      }
    })

    // this.login()
    app.setNavigationBarColor();
    // console.log("登录: " + JSON.stringify(app.globalData.userInfo))
    if(app.globalData.userInfo == null || app.globalData.userInfo == undefined || app.globalData.userInfo.user_id == null){
      
    }else {
      // console.error(JSON.stringify(app.globalData.userInfo))
      wx.reLaunch({
        // url: '/packageA/pages/select_community/select_community'
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 重新获取用户信息
   */
  getUserInfo: function(e) {
    if (e.detail.errMsg == "getUserInfo:ok") {
      app.globalData.wxUserInfo = e.detail.userInfo;
      this.setData({
        wxUserInfo: app.globalData.wxUserInfo
      });
      wx.showLoading({
        title: '正在登录中..',
      });
      // this.login()
      wx.login({
        success: res => {
          const accountInfo = wx.getAccountInfoSync();
          app.wxGetRequest("/wechart/mine/authorize", {
            js_code: res.code,
            applet_id: accountInfo.miniProgram.appId,
            name: app.globalData.wxUserInfo["nickName"],
            head_img: app.globalData.wxUserInfo["avatarUrl"]
          }).then(result => {
            // console.log("用户信息: " + JSON.stringify(result))
            app.globalData.userInfo=result.data.data;
            wx.setStorageSync('user_id', app.globalData.userInfo["user_id"]);
            wx.setStorageSync('people_id', app.globalData.userInfo["people_id"]);
            wx.setStorageSync('name', app.globalData.userInfo["name"]);
            if (!app.globalData.userInfo["people_id"]) {
              wx.hideLoading();
              Toast.show({
                type: 'success',
                message: "登录成功!",
              });
              setTimeout(() => {
                wx.reLaunch({
                  url: '/packageA/pages/select_community/select_community'
                })
              }, 1000);
              return;
            }
            wx.showLoading({
              title: '正在登录中..',
            })
            app.isBindCommunity().then(result => {
              wx.hideLoading();
              Toast.show({
                type: 'success',
                message: "登录成功!",
              });
              setTimeout(() => {
                wx.reLaunch({
                  url: '/packageA/pages/select_community/select_community'
                })
              }, 1000);
            });
          });
        }
      });
    } else {
      app.globalData.wxUserInfo = null;
      this.setData({
        wxUserInfo: app.globalData.wxUserInfo
      });
    }
  },

  login: function(){
    let than = this
    wx.login({
      success: res => {
        const accountInfo = wx.getAccountInfoSync();
        app.wxGetRequest("/wechart/mine/authorize", {
          js_code: res.code,
          applet_id: accountInfo.miniProgram.appId,
          name: app.globalData.wxUserInfo["nickName"],
          head_img: app.globalData.wxUserInfo["avatarUrl"]
        }).then(result => {
          app.globalData.userInfo=result.data.data;
          wx.setStorageSync('user_id', app.globalData.userInfo["user_id"]);
          wx.setStorageSync('people_id', app.globalData.userInfo["people_id"]);
          wx.setStorageSync('name', app.globalData.userInfo["name"]);
          if (!app.globalData.userInfo["people_id"]) {
            wx.hideLoading();
            Toast.show({
              type: 'success',
              message: "登录成功!",
            });
            setTimeout(() => {
              wx.reLaunch({
                url: '/packageA/pages/select_community/select_community'
              })
            }, 1000);
            return;
          }
          wx.showLoading({
            title: '正在登录中..',
          })
          app.isBindCommunity().then(result => {
            wx.hideLoading();
            Toast.show({
              type: 'success',
              message: "登录成功!",
            });
            setTimeout(() => {
              wx.reLaunch({
                url: '/packageA/pages/select_community/select_community'
              })
            }, 1000);
          });
        });
      }
    });
    
  }
})